// pages/buyCar/buyCar.js
var app = getApp();
const getBuyCarInfoUrl = "/ShopCart/cartInfo";
const delBuyCarGoodsUrl = "/ShopCart/delCartGoods";
const payForBuyCarUrl = "/ShopCart/goPay";
const upDateNumUrl = '/ShopCart/updateGoodsNum';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: 1,//是否显示加载中图标
    postage_money: 0, //弹层里面需要显示的运费
    shop_id: 0, //要跳转的店铺ID
    is_enough: 0, //是否显示去凑单弹层
    goods_attr_id: 0, //商品属性ID
    winHeight: 0, //窗口高度
    winWidth: 0, //窗口宽度
    sys_status: 0, //判断是否为审核状态
    goods_id: 0, //更新商品数量时的商品ID
    goodsIds: '', //需要支付的商品ID列表
    cart_ids: '', //需要支付的商品属性ID列表
    statementGold: 0, //需要结算的金币
    statementMoney: 0.00, //需要结算的金额
    statementNum: 0, //需要结算的商品数量
    isAll: 0, //判断是否全选
    filesSourceUri: '', //存储静态资源文件地址
    shopList: [] //存储购物车信息列表
  },
  closeIsEnoughMask: function() {
    this.setData({
      is_enough: 0
    })
  },
  // 阻止点击
  preventEvent: function() {

  },
  // 跳转商品详情页面
  goGoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.goods_id,
    })
  },
  // 跳转购物车
  goBuyCar: function() {
    wx.reLaunch({
      url: '/pages/buyCar/buyCar',
    })
  },
  // 跳转搜索
  goSearch: function() {
    wx.reLaunch({
      url: '/pages/search/index',
    })
  },
  // 跳转我的
  goMy: function() {
    wx.reLaunch({
      url: '/pages/my/my',
    })
  },
  // 返回首页
  goHome: function() {
    wx.reLaunch({
      url: '/pages/home/home'
    })
  },
  // 去凑运费
  goShop: function(e) {
    console.log(e);
    if (e.currentTarget.dataset.type == 1) {
      var postage_money = e.currentTarget.dataset.postage_money;
    } else {
      var postage_money = this.data.postage_money;
    }
    var shop_id = e.currentTarget.dataset.shop_id;

    wx.navigateTo({
      url: '/pages/shop/shop?shop_id=' + shop_id + '&postage_money=' + postage_money,
    })
  },
  // 更新商品数量
  upDateNum: function(goodsId, goodsNum, shopIndex, goods_attr_id) {
    var _this = this;
    var goodsIndex = _this.data.goodsIndex;
    var shopList = _this.data.shopList;
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      type: app.setConfig.type,
      goods_id: goodsId,
      goods_attr_id: goods_attr_id,
      num: goodsNum
    };
    app.post(upDateNumUrl, requestData, function(res) {
      if (res.code == 2000) {
        var shopList = _this.data.shopList;
        shopList[shopIndex].postage_money = res.data.postage_money;
        shopList[shopIndex].goods[goodsIndex].num = goodsNum;
        _this.setData({
          shopList: shopList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  bindInput: function(e) {
    // console.log(e);
    var shopIndex = e.target.dataset.shop_index;
    var goodsIndex = e.target.dataset.goods_index;
    var goods_id = e.target.dataset.goods_id;
    this.setData({
      shopIndex: shopIndex,
      goodsIndex: goodsIndex,
      goods_id: goods_id
    })
  },
  // 获取商品数量
  getGoodsNum: function(e) {
    var _this = this;
    var theGoodsNum = Number(e.detail.value);
    var shopIndex = _this.data.shopIndex;
    var goodsIndex = _this.data.goodsIndex;
    var goods_id = _this.data.goods_id;
    var shopList = _this.data.shopList;
    var total_num = Number(shopList[shopIndex].goods[goodsIndex].total_num);
    var goods_attr_id = shopList[shopIndex].goods[goodsIndex].goods_attr_id;
    if (theGoodsNum > total_num) {
      wx.showToast({
        title: '没有更多商品了哦~',
        icon: 'error',
        duration: 2000
      });
      _this.upDateNum(goods_id, total_num, shopIndex, goods_attr_id);
      // return false;
    } else if (theGoodsNum < 1) {
      wx.showToast({
        title: '不能再少了哦~',
        icon: 'error',
        duration: 2000
      });
    } else {
      shopList[shopIndex].goods[goodsIndex].num = theGoodsNum;
      _this.upDateNum(goods_id, theGoodsNum, shopIndex, goods_attr_id);
    }
  },
  // 改变商品数量
  changeNum: function(e) {
    // console.log(e);
    var _this = this;
    var type = e.target.dataset.type;
    var shopIndex = e.target.dataset.shop_index;
    var goodsIndex = e.target.dataset.goods_index;
    var goods_id = e.target.dataset.goods_id;
    var shopList = _this.data.shopList;
    this.setData({
      shopIndex: shopIndex,
      goodsIndex: goodsIndex,
      goods_id: goods_id
    })
    if (type == 1) {
      if (shopList[shopIndex].goods[goodsIndex].num < shopList[shopIndex].goods[goodsIndex].total_num) {
        shopList[shopIndex].goods[goodsIndex].num = Number(shopList[shopIndex].goods[goodsIndex].num) + 1;
        _this.upDateNum(goods_id, shopList[shopIndex].goods[goodsIndex].num, shopIndex, shopList[shopIndex].goods[goodsIndex].goods_attr_id);
      } else {
        wx.showToast({
          title: '没有更多商品啦~',
          icon: 'none',
          duration: 2000
        })
      }

    } else {
      if (shopList[shopIndex].goods[goodsIndex].num > 1) {
        shopList[shopIndex].goods[goodsIndex].num = Number(shopList[shopIndex].goods[goodsIndex].num) - 1;
        _this.upDateNum(goods_id, shopList[shopIndex].goods[goodsIndex].num, shopIndex, shopList[shopIndex].goods[goodsIndex].goods_attr_id);
      } else {
        wx.showToast({
          title: '商品数量已经是最少了呦',
          icon: 'none',
          duration: 2000
        })
      }

    }
    _this.setData({
      shopList: shopList
    });
    var changePrice = {
      shopIndex: shopIndex,
      goodsIndex: goodsIndex,
      is_checked: 1
    }
    _this.statementGoods(changePrice);
  },
  // 支付购物车跳转订单详情页
  settlementEvent: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var shopList = _this.data.shopList;
    if (_this.data.statementNum == 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (_this.data.is_enough == 0) {
      for (var i = 0; i < shopList.length; i++) {
       
          for (var j = 0; j < shopList[i].goods.length; j++) {
            if (shopList[i].goods[j].isChecked == 1 || shopList[i].isChecked == 1) {
            if (shopList[i].postage_money != 0) {
              console.log
              _this.setData({
                postage_money: shopList[i].postage_money,
                shop_id: shopList[i].shop_id,
                is_enough: 1
              })
              return false;
            }

          }
        }
        
      }
    }
    wx.navigateTo({
      url: '/pages/payForBuyCar/payForBuyCar?goods_ids=' + JSON.stringify(_this.data.goodsIds) + '&cart_ids=' + JSON.stringify(_this.data.cart_ids) + '&is_all=' + _this.data.isAll + '&money=' + _this.data.statementMoney,
    })
  },
  // 删除购物车的商品
  delBuyCarGoods: function(e) {
    var _this = this;
    var shopIndex = e.target.dataset.shop_index,
      goodsIndex = e.target.dataset.goods_index,
      goods_attr_id = e.target.dataset.goods_attr_id,
      shopList = _this.data.shopList;
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      type: app.setConfig.type,
      goods_id: e.target.dataset.goods_id,
      goods_attr_id: goods_attr_id
    }
    wx.showModal({
      title: '提示',
      content: '确定要将这件商品从购物车中移除吗',
      success: function(res) {
        if (res.confirm) {
          app.post(delBuyCarGoodsUrl, requestData, function(res) {
            if (res.code == 2000) {
              shopList[shopIndex].goods.splice(goodsIndex, 1);
              shopList[shopIndex].postage_money = res.data.postage_money;
              for (var i = 0; i < shopList.length; i++) {
                if (shopList[i].goods.length == 0) {
                  _this.getBuyCarInfo();
                }
              }

              _this.setData({
                shopList: shopList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 2000
              });
              var changePrice = {
                shopIndex: shopIndex,
                goodsIndex: goodsIndex,
                is_checked: 0
              }
              _this.statementGoods(changePrice);
            }else{
              wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 2000
              });
            }
          })
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    var configs = wx.getStorageSync('configs');
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth;
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: clientHeight,
          filesSourceUri: configs.static_url_http,
          sys_status: configs.sys_status
        })
      }
    });
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getBuyCarInfo();
    }
  },
  // 获取购物车信息
  getBuyCarInfo: function() {
    var _this = this;
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      type: app.setConfig.type
    }
    app.post(getBuyCarInfoUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          isLoading: 0,
          shopList: res.data.cart
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 点击全选
  chooseAll: function(e) {
    var _this = this;
    var shopList = _this.data.shopList,
      statementNum = 0,
      statementGold = 0,
      statementMoney = 0.00;
    for (var i = 0; i < shopList.length; i++) {
      shopList[i].isChecked = 1;
      for (var j = 0; j < shopList[i].goods.length; j++) {
        shopList[i].goods[j].isChecked = 1;
        statementGold = statementGold + Number(shopList[i].goods[j].gold_coin) * Number(shopList[i].goods[j].num);
        statementMoney = statementMoney + Number(shopList[i].goods[j].buy_price) * Number(shopList[i].goods[j].num);
        statementNum = statementNum + Number(shopList[i].goods[j].num);
      }
    }
    statementMoney = statementMoney.toFixed(2);
    _this.setData({
      statementMoney: statementMoney,
      statementGold: statementGold,
      statementNum: statementNum,
      isAll: 1
    });
  },
  // 取消全选
  cancelAll: function(e) {
    var _this = this;
    var shopList = _this.data.shopList;
    for (var i = 0; i < shopList.length; i++) {
      shopList[i].isChecked = 0;
      for (var j = 0; j < shopList[i].goods.length; j++) {
        shopList[i].goods[j].isChecked = 0;
      }
    }
    _this.setData({
      cart_ids: '',
      goodsIds: '',
      shopList: shopList,
      statementMoney: 0.00,
      statementGold: 0,
      statementNum: 0,
      isAll: 0
    });
  },
  // 选择店铺并且计算
  statementShop: function(e) {
    var _this = this;
    var shopIndex = e.target.dataset.shop_index,
      isChecked = e.target.dataset.is_checked,
      shopList = _this.data.shopList,
      statementNum = 0,
      statementGold = 0,
      statementMoney = 0.00,
      cart_ids = [],
      goodsIds = [];
    shopList[shopIndex].isChecked = isChecked;
    for (var k = 0; k < shopList[shopIndex].goods.length; k++) {
      shopList[shopIndex].goods[k].isChecked = isChecked;
    }
    for (var i = 0; i < shopList.length; i++) {
      if (shopList[i].isChecked == 1) {
        for (var j = 0; j < shopList[i].goods.length; j++) {
          goodsIds.push(shopList[i].goods[j].goods_id);
          cart_ids.push(shopList[i].goods[j].cart_id);
          statementGold = statementGold + Number(shopList[i].goods[j].gold_coin) * Number(shopList[i].goods[j].num);
          statementMoney = statementMoney + Number(shopList[i].goods[j].buy_price) * Number(shopList[i].goods[j].num);
          statementNum = statementNum + Number(shopList[i].goods[j].num);
        }
      } else {
        for (var j = 0; j < shopList[i].goods.length; j++) {
          if (shopList[i].goods[j].isChecked == 1) {
            goodsIds.push(shopList[i].goods[j].goods_id);
            cart_ids.push(shopList[i].goods[j].cart_id);
            statementGold = statementGold + Number(shopList[i].goods[j].gold_coin) * Number(shopList[i].goods[j].num);
            statementMoney = statementMoney + Number(shopList[i].goods[j].buy_price) * Number(shopList[i].goods[j].num);
            statementNum = statementNum + Number(shopList[i].goods[j].num);
          }
        }
      }
    }
    statementMoney = statementMoney.toFixed(2);
    _this.setData({
      cart_ids: cart_ids,
      goodsIds: goodsIds,
      statementMoney: statementMoney,
      statementGold: statementGold,
      statementNum: statementNum,
      shopList: shopList,
      isAll: 0
    });
    if (isChecked == 1) {
      _this.isAllChecked(0);
    }
  },
  // 选择商品并且计算
  statementGoods: function(e) {
    var _this = this;
    var shopList = _this.data.shopList,
      statementNum = 0,
      statementGold = 0,
      statementMoney = 0.00,
      cart_ids = [],
      goodsIds = [];
    if (e.target) {
      var shopIndex = e.target.dataset.shop_index,
        goodsIndex = e.target.dataset.goods_index,
        is_checked = e.target.dataset.is_checked;
      shopList[shopIndex].isChecked = 0;
      shopList[shopIndex].goods[goodsIndex].isChecked = is_checked;
    } else {
      var shopIndex = e.shop_index,
        goodsIndex = e.goods_index,
        is_checked = e.is_checked;
    }

    for (var i = 0; i < shopList.length; i++) {
      if (shopList[i].isChecked == 1) {
        for (var j = 0; j < shopList[i].goods.length; j++) {
          goodsIds.push(shopList[i].goods[j].goods_id);
          cart_ids.push(shopList[i].goods[j].cart_id);
          statementGold = statementGold + Number(shopList[i].goods[j].gold_coin) * Number(shopList[i].goods[j].num);
          statementMoney = statementMoney + Number(shopList[i].goods[j].buy_price) * Number(shopList[i].goods[j].num);
          statementNum = statementNum + Number(shopList[i].goods[j].num);
        }
      } else {
        for (var j = 0; j < shopList[i].goods.length; j++) {
          if (shopList[i].goods[j].isChecked == 1) {
            goodsIds.push(shopList[i].goods[j].goods_id);
            cart_ids.push(shopList[i].goods[j].cart_id);
            statementGold = statementGold + Number(shopList[i].goods[j].gold_coin) * Number(shopList[i].goods[j].num);
            statementMoney = statementMoney + Number(shopList[i].goods[j].buy_price) * Number(shopList[i].goods[j].num);
            statementNum = statementNum + Number(shopList[i].goods[j].num);
          }
        }
      }
    };
    statementMoney = statementMoney.toFixed(2);
    _this.setData({
      cart_ids: cart_ids,
      goodsIds: goodsIds,
      statementMoney: statementMoney,
      statementGold: statementGold,
      statementNum: statementNum,
      shopList: shopList,
      isAll: 0
    })
    if (is_checked == 1) {
      _this.isAllChecked(1);
    }
  },
  // 判断该店铺下的商品是否都选中，以及判断是否所有的店铺都已经选中
  isAllChecked: function(type) {
    /**
     * type
     * 0 点击店铺
     * 1 点击商品
     */

    var _this = this;
    var isAll = _this.data.isAll,
      shopList = _this.data.shopList,
      shopNum = 0,
      goodsNum = 0,
      goodsShopNum = 0;
    for (var i = 0; i < shopList.length; i++) {
      goodsNum = 0;

      if (shopList[i].isChecked == 1) {
        shopNum = shopNum + 1;
      }
      if (shopNum == shopList.length) {
        isAll = 1
      } else {
        isAll = 0
      }
      if (type == 1) {
        for (var j = 0; j < shopList[i].goods.length; j++) {
          goodsShopNum = 0;
          if (shopList[i].goods[j].isChecked == 1) {
            goodsNum++;
          }
          if (goodsNum == shopList[i].goods.length) {
            shopList[i].isChecked = 1;
          } else {
            shopList[i].isChecked = 0;
          }
          for (var m = 0; m < shopList.length; m++) {
            if (shopList[m].isChecked == 1) {
              goodsShopNum++;
            }
            if (goodsShopNum == shopList.length) {
              isAll = 1
            } else {
              isAll = 0
            }
          }
        }

      }
    };
    _this.setData({
      shopList: shopList,
      isAll: isAll
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      is_enough: 0,
      cart_ids: '',
      goodsIds: '', //需要支付的商品ID列表
      statementGold: 0, //需要结算的金币
      statementMoney: 0.00, //需要结算的金额
      statementNum: 0, //需要结算的商品数量
      isAll: 0 //判断是否全选
    })
    this.loop();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})